<script setup>
import ProductBasicInfo from '@/views/product/ProductBasicInfo.vue';
import ProductDescription from "@views/product/ProductDescription.vue";
import ProductComments from "@views/product/ProductComments.vue";
import RecommendedProducts from "@views/product/RecommendedProducts.vue";
import ProductVideo from "@views/product/ProductVideo.vue";
import NavBar from "@views/common/NavBar.vue";
import Footer from "@views/common/Footer.vue";
import {ref, reactive, onMounted} from 'vue'
import apis, {IMG_BASE_PATH} from "@/config/api-config.js";
import getResponse from "@assets/js/http-client.js";
import {ElMessage} from "element-plus";
import {useRoute} from 'vue-router';
import FindPassword from "@views/FindPassword.vue";
import Modal from "@views/common/Modal.vue";
import Register from "@views/Register.vue";
import Login from "@views/Login.vue";
import {useRouter} from "vue-router";

const router = useRouter();
const route = useRoute();
//商品基本信息组件引用
const productInfoRef = ref(null);
//会员用户
const user = ref({});
//模态框信息
const modalConfig = reactive({
  visible: false,
  //1:显示会员登录模态框;2:显示会员注册模态框;3:显示找回密码或忘记密码模态框
  type: 1
});
//关闭模态框
const closeModal = () => {
  modalConfig.visible = false;
  modalConfig.type = 1;//默认显示登录模态框
}
//打开模态框
const showModal = (type) => {
  if (!(1 === type || 2 === type || 3 === type || 0 === type)) {
    ElMessage({
      message: '打开模态框失败,未知的页面',
      type: 'error',
      duration: 2000
    });
    return;
  }
  //0表示登录成功后,关闭登录框
  if (0 === type) {
    closeModal();
    getUserInfo();
    return;
  }
  modalConfig.type = type;
  modalConfig.visible = true;
}
const getUserInfo = async () => {
  let token = localStorage.getItem('wemall-token');
  if (token === null) {
    return;
  }
  //如果有token,说明已登录过系统,则根据token获取用户数据
  let url = apis.member.getInfo.url;
  let type = apis.member.getInfo.type;
  //token参数已统一处理,无需再手动添加
  const result = await getResponse(url, type);
  if (200 !== result.code) {
    console.info('获取用户信息失败:', result.message);
    return;
  }
  //console.info('获取用户信息成功:', result.data);
  user.value = result.data;
  let avatar = user.value.avatar;
  if (!avatar) {
    user.value.avatar = 'src/assets/img/member/user_center.png';
  } else {
    user.value.avatar = IMG_BASE_PATH + avatar;
  }
}

// 产品基本信息数据
const productData = ref({
  id: 1001,
  title: '智能无线蓝牙耳机',
  price: 299.00,
  originalPrice: 399.00,
  discount: '限时8折',
  images: [
    'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=600&q=80',
    'https://images.unsplash.com/photo-1546435770-a3e426bf472b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=600&q=80',
    'https://images.unsplash.com/photo-1572536147248-ac59a8abfa4b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=600&q=80'
  ],
  rating: 4.8,
  reviewCount: 128,
  stock: 150,
  sales: 3200,
  brand: 'TechSound',
  model: 'TS-BT2023',
  colorOptions: ['黑色', '白色', '蓝色'],
  selectedColor: '黑色',
  specs: [
    {name: '蓝牙版本', value: '5.2'},
    {name: '电池续航', value: '30小时'},
    {name: '充电时间', value: '1.5小时'},
    {name: '重量', value: '250g'},
    {name: '防水等级', value: 'IPX5'}
  ]
})

// 产品描述数据
const descriptionData = ref({
  paragraphs: [
    '这是一个智能无线蓝牙耳机，支持蓝牙5.2协议，具有强大的音频处理能力和出色的降噪效果。',
    '它采用了先进的无线充电技术，充电时间仅需1.5小时，续航能力可达30小时。',
    '该蓝牙耳机还配备了防水设计，能够在任何环境下使用，保护用户的隐私和安全。',
    '它的重量仅为250g，尺寸小巧，方便携带和使用。',
    '该蓝牙耳机还支持多设备连接，用户可以同时在多部手机、平板电脑和智能手表上使用。',
    '它的音质非常清晰，能够满足用户的 listening 需求。',
    '该蓝牙耳机还配备了一个方便的触控板，用户可以通过简单的手势控制手机的功能。',
    '它的使用非常方便，用户只需要将蓝牙耳机插入手机的耳机孔中，即可开始使用。',
    '该蓝牙耳机还支持语音识别功能，用户可以通过语音指令控制手机的功能。'],
  features: [
    '智能无线蓝牙耳机',
    '支持蓝牙5.2协议',
    '强大的音频处理能力',
    '出色的降噪效果',
    '防水设计',
    '重量小巧',
    '多设备连接',
    '音质清晰',
    '方便的触控板',
    '简单易用',
    '语音识别功能'
  ]
})

// 产品评论数据
const commentsData = ref([
  {
    id: 1,
    userName: '张三',
    avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
    rating: 5,
    content: '音质非常棒，降噪效果出色，佩戴舒适，强烈推荐！',
    date: '2023-10-15',
    images: []
  },
  {
    id: 2,
    userName: '李四',
    avatar: 'https://randomuser.me/api/portraits/women/44.jpg',
    rating: 4,
    content: '性价比很高，续航能力不错，就是充电盒有点大。',
    date: '2023-10-10',
    images: [
      'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=300&q=80'
    ]
  },
  {
    id: 3,
    userName: '王五',
    avatar: 'https://randomuser.me/api/portraits/men/22.jpg',
    rating: 5,
    content: '已经使用一个月了，音质和降噪都很满意，值得购买！',
    date: '2023-09-28',
    images: []
  }
])

// 推荐产品数据
const recommendedProductsData = ref([
  {
    id: 2001,
    name: '运动蓝牙耳机',
    price: 199.00,
    originalPrice: 259.00,
    image: 'https://images.unsplash.com/photo-1572536147248-ac59a8abfa4b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=300&q=80',
    rating: 4.6,
    reviewCount: 89
  },
  {
    id: 2002,
    name: '头戴式降噪耳机',
    price: 599.00,
    originalPrice: 799.00,
    image: 'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=300&q=80',
    rating: 4.9,
    reviewCount: 215
  },
  {
    id: 2003,
    name: '入耳式无线耳机',
    price: 159.00,
    originalPrice: 199.00,
    image: 'https://images.unsplash.com/photo-1546435770-a3e426bf472b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=300&q=80',
    rating: 4.5,
    reviewCount: 67
  },
  {
    id: 2004,
    name: '游戏专用耳机',
    price: 399.00,
    originalPrice: 499.00,
    image: 'https://images.unsplash.com/photo-1583394838336-acd977736f90?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=300&q=80',
    rating: 4.7,
    reviewCount: 142
  }
])

// 处理添加到购物车事件
const handleAddToCart = async () => {
  if (!user.value || !user.value.id) {
    showModal(1)
    return
  }
  let url = apis.cart.add.url;
  let type = apis.cart.add.type;
  let params = {prodId: productData.value.id};
  const result = await getResponse(url, type, params);
  if (200 !== result.code) {
    ElMessage.error(result.message);
    return;
  }
  ElMessage.success({
    message: '加入购物车成功', duration: 1500, type: 'success', onClose: () => {
      router.push('/member/shopping_cart');
    }
  });

}

// 处理立即购买事件
const handleBuyNow = () => {
  if (!user.value || !user.value.id) {
    showModal(1)
    return
  }
  ElMessage.success('购买成功');
}
/**
 * 添加或取消商品收藏
 * @returns {Promise<void>}
 */
const handleToggleFavorite = async () => {
  if (!user.value || !user.value.id) {
    showModal(1)
    return
  }
  if (productInfoRef.value.isFavorite) {
    await handleRemoveFavorite();
  } else {
    await handleAddToFavorite();
  }
}
/**
 * 移除收藏
 * @returns {Promise<void>}
 */
const handleRemoveFavorite = async () => {
  if (!user.value || !user.value.id) {
    showModal(1)
    return
  }
  let url = apis.collect.delete.url;
  let type = apis.collect.delete.type;
  let params = {prodId: productData.value.id};
  const result = await getResponse(url, type, params);
  if (200 !== result.code) {
    ElMessage.error(result.message);
    return;
  }
  productInfoRef.value.isFavorite = false;
  ElMessage.success('取消收藏成功');
}
// 处理添加到收藏事件
const handleAddToFavorite = async () => {
  if (!user.value || !user.value.id) {
    showModal(1)
    return
  }
  let url = apis.collect.add.url;
  let type = apis.collect.add.type;
  let params = {prodId: productData.value.id};
  const result = await getResponse(url, type, params);
  if (200 !== result.code) {
    ElMessage.error(result.message);
    return;
  }
  productInfoRef.value.isFavorite = true;
  ElMessage.success('加入收藏成功');
}

// 处理提交评论事件
const handleSubmitComment = (comment) => {
  console.log('提交评论:', comment)
  // 这里可以调用评论相关的API
}
onMounted(async () => {
  await getUserInfo();
  await loadProductDetails();
  await containsFavorite();
});
const loadProductDetails = async () => {
  let id = route.params.id;
  let url = apis.product.details.url.replace('{id}', id);
  let type = apis.product.details.type;
  let result = await getResponse(url, type);
  if (200 !== result.code) {
    ElMessage.error(result.message);
    return
  }
  let product = result.data;
  if (!product) {
    ElMessage.error('商品不存在或已下架');
    return
  }
  let specs = product.specs;
  if (specs) {
    product.specs = JSON.parse(specs);
  }
  productData.value = product;
  console.info('商品详情:', productData.value)
}
const containsFavorite = async () => {
  if (!user.value || !user.value.id) {
    return false;
  }
  let url = apis.collect.contains.url;
  let type = apis.collect.contains.type;
  let params = {prodId: productData.value.id};
  let result = await getResponse(url, type, params);
  if (200 !== result.code) {
    ElMessage.error(result.message);
    return false;
  }
  let count = result.data;
  if (1 === count) {
    productInfoRef.value.isFavorite = true;
  }
  if (count > 1 || count < 0) {
    ElMessage.warning('该商品收藏状态异常')
  }
}
</script>

<template>
  <NavBar @show-modal="showModal" :user="user" @clean:user="user ={}"/>
  <div>
    <ProductBasicInfo :product="productData" @add-to-cart="handleAddToCart" @buy-now="handleBuyNow"
                      @add-to-favorite="handleToggleFavorite" ref="productInfoRef"/>
    <ProductDescription :description="descriptionData"/>
    <ProductComments :comments="commentsData" @submit-comment="handleSubmitComment"/>
    <RecommendedProducts :products="recommendedProductsData"/>
    <ProductVideo video-src="product_video.mp4"/>
    <Footer/>
    <Modal :is-visible="modalConfig.visible" @close-modal="closeModal">
      <Login v-if="1==modalConfig.type" @show-modal="showModal"></Login>
      <Register v-else-if="2==modalConfig.type" @show-modal="showModal"></Register>
      <FindPassword v-else-if="3==modalConfig.type" @show-modal="showModal"></FindPassword>
      <div v-else>
        <span style="color:red">模态框类型错误</span>
      </div>
    </Modal>
  </div>
</template>

<style scoped>

</style>